package com.alibaba.moco.springboot;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.moco.MocoScriptRunner;
import com.alibaba.moco.gitlab.GitlabApiUtil;
import com.alibaba.moco.gitlab.GitlabFileResVo;

import net.sf.json.JSONObject;
/**
 * 脚本加载拦截器
 * @author wb-lj240895
 *
 */
public class ScriptInterceptor implements HandlerInterceptor  {
	
	private static final String RESOURCE_JSON = "resources/json";
	private static final String SUFFIX_JSON = ".json";
	//private static final String SUFFIX_GROOVY = ".groovy";
	

	private static final Logger logger = LoggerFactory.getLogger(ScriptInterceptor.class);
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String uri = request.getRequestURI();
		logger.info(request.getRemoteHost());
		if (!StringUtils.isBlank(uri)){
			//移除后缀
			if (uri.contains(".")){
				String[] uris = uri.split("\\.");
				uri = uris[0];
			}
			//先做json处理
			GitlabFileResVo source = null;
			String content = null;
			
			source = GitlabApiUtil.getFileContent(RESOURCE_JSON + uri + SUFFIX_JSON);
			
			if (source != null){
				//寻找到静态json资源  返回
				content = source.getContent();
				logger.info("静态资源url:{},data:{}", uri, content);
			} else {
				Object result = MocoScriptRunner.excuteScriptCache(request, uri);
				content = JSONObject.fromObject(result).toString();
				if (!StringUtils.isBlank(content)) logger.info("执行脚本url:{},data:{}", uri, content);
				else return true; //脚本和json文件都未找到时跳过顾虑器
			}
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(content);
			response.getWriter().flush();
			response.getWriter().close();
			return false;
		}
		return true;
	}

}
